package org.jeecg.modules.charge.controller;


import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.modules.charge.entity.ChargeCollect;
import org.jeecg.modules.charge.model.ChargeTables;
import org.jeecg.modules.charge.service.IChargeMethodService;
import org.jeecg.modules.charge.service.impl.ChargeBillsServiceImpl;
import org.jeecg.vo.charge.ChargeMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
* @Description: 日收款汇总表
* @Author: jeecg-boot
* @Date:   2019-10-29
* @Version: V1.0
*/
@Slf4j
@Api(tags="日收款汇总表")
@RestController
@RequestMapping("/b/charge/collect")
public class ChargeCollectController {

    @Autowired
    private ChargeBillsServiceImpl chargeBillsService;
    @Autowired
    private IChargeMethodService chargeMethodService;
    /**
     * 收款方式
     * @param
     * @param req
     * @return
     */
    @GetMapping(value = "/getByTables")
    public Result<List<ChargeTables>> getChargeBillsAll(HttpServletRequest req) {
        Result<List<ChargeTables>> result = new Result<List<ChargeTables>>();
        List<ChargeTables> tables = new ArrayList<ChargeTables>();
        try {
            LoginUser user =  SsoUtil.getLoginUser();
            List<ChargeMethod> methodList =   chargeMethodService.getPayMethodList(9,user.getTenantId());
            for(ChargeMethod chargeMethod:methodList){
                ChargeTables chargeTables =new ChargeTables();
                chargeTables.setTitle(chargeMethod.getMethodName());
                chargeTables.setAlign("center");
                chargeTables.setWidth("100px");
                chargeTables.setDataIndex(StringUtils.getPinYinHeadChar(chargeMethod.getMethodName()));
                tables.add(chargeTables);
            }
            result.setSuccess(true);
            result.setResult(tables);
        }catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        return result;
    }

    /**
     * 汇总日报表
     * @param
     * @param req
     * @return
     */
    @PostMapping(value = "/getCollectPort")
    public Result<List<ChargeCollect>> getCollectPort(@RequestBody ChargeCollect chargeCollect,
                                                          HttpServletRequest req) {
        Result<List<ChargeCollect>> result = new Result<List<ChargeCollect>>();
        try {
                    List<ChargeCollect> collectList = new ArrayList<ChargeCollect>();
                    if(chargeCollect.getFeeCodes() != null && chargeCollect.getFeeCodes().size()>0){
                        for(String code:chargeCollect.getFeeCodes()){
                            ChargeCollect ect = new ChargeCollect();
                            chargeCollect.setFeeCode(code);
                            List<ChargeCollect> collect =  chargeBillsService.getDayCollect(chargeCollect);
                            if(collect != null && collect.size()> 0){
                                for (ChargeCollect co:collect){
                                    co.setMethodName(StringUtils.getPinYinHeadChar(co.getMethodName()));
                                }
                                ect.setCollects(collect);
                                ect.setFeeName(chargeBillsService.getByfeeName(code));
                                collectList.add(ect);
                            }
                        }
                    }
            result.setSuccess(true);
            result.setResult(collectList);
        }catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param
     * @param response
     */
    @PostMapping(value = "/exportXls")
    public void exportXls(@RequestBody ChargeCollect chargeCollect, HttpServletResponse response) {
        XSSFWorkbook book = new XSSFWorkbook();
        try {
            LoginUser user =  SsoUtil.getLoginUser();
            List<ChargeMethod> methodList =   chargeMethodService.getPayMethodList(9,user.getTenantId());
            XSSFSheet sheet = book.createSheet("mySheent");
            if(methodList != null && methodList.size() > 0){ //头部获取
                String [] vals = new String[methodList.size()+2];
                vals[0] = "收费项目";
                for(int i=0;i < methodList.size();i++){
                    vals[i+1] = methodList.get(i).getMethodName();
                }
                vals[methodList.size()+1] = "合计金额";
                createExcel(sheet, 0, vals);
            }
            if(chargeCollect.getFeeCodes() != null && chargeCollect.getFeeCodes().size()>0){
                 for(int i=0;i<chargeCollect.getFeeCodes().size();i++){
                    chargeCollect.setFeeCode(chargeCollect.getFeeCodes().get(i));
                    List<ChargeCollect> collect =  chargeBillsService.getDayCollect(chargeCollect);
                    if(collect != null && collect.size()> 0) {
                        String[] vals2 = new String[collect.size()+2];
                        vals2[0] = chargeBillsService.getByfeeName(chargeCollect.getFeeCodes().get(i));
                        Double sum = 0.0;
                        for (int j = 0; j < collect.size(); j++) {
                            if(collect.get(j).getMoney() > 0){
                                vals2[j+1] = collect.get(j).getMoney().toString();
                                sum += collect.get(j).getMoney();
                            }else{
                                vals2[j+1] = "0";
                            }
                        }
                        BigDecimal bigsum1 = new BigDecimal(sum);
                        Double sum1 = bigsum1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        vals2[collect.size()+1] = sum1.toString();
                        createExcel(sheet, i+1, vals2);
                    }
                }
                book.write(generateResponseExcel("用户列表",response));
            }

        }catch(Exception e){
            e.printStackTrace();
        }
    }
    /**
       * @param excelName
       *   要生成的文件名字
       * @return
       * @throws IOException
       */
    private ServletOutputStream generateResponseExcel(String excelName, HttpServletResponse response) throws IOException {
        excelName = excelName == null || "".equals(excelName) ? "excel" : URLEncoder.encode(excelName, "UTF-8");
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + excelName + ".xlsx");
        return response.getOutputStream();
    }
    private void createExcel(XSSFSheet sheet, int rowNo, String[] vals)  {
        if (vals.length > 0) {
            XSSFRow row = sheet.createRow(rowNo);
            for (int i = 0; i < vals.length; i++) {
                String val = vals[i];
                XSSFCell cell = row.createCell(i);
                cell.setCellValue(val);
            }
        }
    }
}
